<template>
	<view class="container">
		<view class="result-container">
			<!-- 顶部标题 -->
			<view class="header">
				<text class="result-title">测试结果</text>
			</view>

			<!-- 根据 testId 动态渲染不同的结果展示 -->
			<view v-if="testId === '1'">
				<!-- 风险等级卡片 -->
				<view class="card risk-card">
					<text class="card-title">风险等级</text>
					<text class="risk-level" :class="riskLevelClass">{{ result.riskLevel }}</text>
					<text class="risk-description">{{ result.summary.totalScoreDescription }}</text>
				</view>

				<!-- 总均分卡片 -->
				<view class="card score-card">
					<text class="card-title">总均分</text>
					<text class="total-score">{{ result.totalAverageScore }}</text>
				</view>

				<!-- 各维度得分列表 -->
				<view class="card dimension-card">
					<text class="card-title">各维度得分</text>
					<view class="dimension-list">
						<view class="dimension-item" v-for="factor in result.factors" :key="factor.name">
							<text class="dimension-name">{{ factor.name }}</text>
							<view class="progress-bar">
								<view class="progress" :style="{ width: getProgressWidth(factor.averageScore) }"></view>
							</view>
							<text class="dimension-score">{{ factor.averageScore }}</text>
							<text class="dimension-description">{{ factor.description }}</text>
						</view>
					</view>
				</view>
			</view>

			<view v-else-if="testId === '2'">
				<!-- 风险等级卡片 -->
				<view class="card risk-card">
					<text class="card-title">风险等级</text>
					<text class="risk-level" :class="riskLevelClass">{{ result.riskLevel }}</text>
				</view>

				<!-- 总得分卡片 -->
				<view class="card score-card">
					<text class="card-title">总得分</text>
					<text class="total-score">{{ result.totalScore }}</text>
				</view>
			</view>

			<view v-else-if="testId === '3'">
				<!-- 短期焦虑卡片 -->
				<view class="card">
					<text class="card-title">短期焦虑</text>
					<text class="score">{{ result.shortTermAnxiety }}</text>
				</view>

				<!-- 长期焦虑卡片 -->
				<view class="card">
					<text class="card-title">长期焦虑</text>
					<text class="score">{{ result.longTermAnxiety }}</text>
				</view>

				<!-- 前20分卡片 -->
				<view class="card">
					<text class="card-title">前20题</text>
					<text class="score">{{ result.front20Score }}</text>
				</view>

				<!-- 后20分卡片 -->
				<view class="card">
					<text class="card-title">后20题</text>
					<text class="score">{{ result.back20Score }}</text>
				</view>
			</view>

			<view v-else>
				<text class="error-message">无效的问卷类型</text>
			</view>

			<!-- AI分析结果区域 -->
			<view class="ai-section">
				<text class="ai-title">AI分析</text>
				<view v-if="isLoading" class="ai-loading">
					<u-empty text="请等待AI分析结果" mode="message">
						<template #icon>
							<u-loading mode="circle" color="#6c8eef" size="40"></u-loading>
						</template>
					</u-empty>
				</view>
				<view v-else class="ai-comment">
					{{aiComment}}
				</view>
			</view>
			
			<!-- 个性化推荐区域 -->
			<view class="recommend-section card" v-if="['低风险', '中风险', '高风险'].includes(result.riskLevel)">
			  <text class="recommend-title">个性化推荐</text>
				<view v-if="['中风险', '高风险'].includes(result.riskLevel)">
				  <text class="recommend-message">建议您预约一次专业的心理咨询，以下是推荐的咨询师：</text>
				  
				  <view class="consultant-card">
					<!-- 咨询师头像 -->
					<image :src="recommendedCon.avatar" class="consultant-avatar" mode="aspectFill" />

					<!-- 咨询师信息 -->
					<view class="consultant-info">
					  <text class="consultant-name">{{ recommendedCon.name }} 咨询师</text>
					  <text class="consultant-desc">从业{{ recommendedCon.experience }}年 · 擅长 {{ recommendedCon.expertise && recommendedCon.expertise.join('、') }}</text>
					</view>

					<!-- 预约按钮 -->
					<u-button type="primary" size="mini" text="立即预约" @click="handleAppointment(recommendedCon)" />
				  </view>
				</view>
				
			    <view v-else>
				  <text class="recommend-message">您的状态良好，推荐您体验心理小游戏或参与留言互动。</text>
				  <u-button type="success" size="mini" text="去玩游戏" @click="navigateTo('/gamePages/games/games')" class="recommend-btn" />
				  <u-button size="mini" text="去留言板" @click="navigateTo('/gamePages/message/message')" class="recommend-btn" />
			    </view>
			</view>

		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			result: {}, // 存储解析后的结果
			testId: "", // 存储问卷类型
			aiComment:"请等待ai分析结果",// ai评价
			isLoading: true ,// 添加加载状态
			recommendedCon:{}
		};
	},
	computed: {
		// 根据风险等级动态设置样式
		riskLevelClass() {
			switch (this.result.riskLevel) {
				case "低风险":
					return "low-risk";
				case "中风险":
					return "medium-risk";
				case "高风险":
					return "high-risk";
				case "不孤独":
					return "low-risk";
				case "低度孤独":
					return "low-risk";
				case "一般偏下孤独":
				    return "medium-risk";
				case "一般孤独":
				    return "medium-risk";
				case "一般偏上孤独":
				    return "high-risk";
				case "高度孤独":
				    return "high-risk";
				default:
					return "";
			}
		},
	},
	methods: {
		navigateTo(path){
			uni.navigateTo({
				url:`${path}`
			})
		},
		//获取推荐咨询师
		async fetchRecommendedCon(){
			try {
			    const res = await uniCloud.callFunction({
			      name: 'getAvailableCons'
			    });
			
			    const consultants = res.result?.data || [];
			
			    if (consultants.length > 0) {
					//随机选择
			      const randomIndex = Math.floor(Math.random() * consultants.length);
			      this.recommendedCon = consultants[randomIndex];
			    } else {
			      this.recommendedCon = {}; // 没有可用咨询师时置空
			    }
				console.log(this.recommendedCon);
			  } catch (err) {
			    console.error('获取可用咨询师失败:', err);
			    this.recommendedCon = {}; // 出错时也置空
			  }
		},
		//跳转到推荐咨询师预约界面
		handleAppointment(consultant) {
			uni.navigateTo({
				url: `/pages/appointment/appoint?uniIdToken=${consultant.uniIdToken}`
			});
		},
		// 计算进度条宽度
		getProgressWidth(score) {
			const maxScore = 4; // 最大分值
			return `${(score / maxScore) * 100}%`;
		},
		// 调用云函数获取AI分析
		async getAIEstimate(resultId) {
			try {
				console.log(uni.getStorageSync("aiContent"))
				const res = await uniCloud.callFunction({
					name: 'aiEstimateResult',
					data: {
						aiContent:uni.getStorageSync("aiContent"),
						testId:this.testId,
						resultId:resultId
						}
				});
				console.log(res)
				if (res.result) {
					this.aiComment = res.result.reply; 
				}
			} catch (e) {
				console.error("AI分析获取失败:", e.detail);
			} finally {
				this.isLoading = false; // 无论成功与否，都设置为非加载状态
			}
			
		}

	},
	async onLoad(options) {
	    try {
	        if (options.result) {
	            this.result = JSON.parse(decodeURIComponent(options.result));
	            this.testId = options.testId || '';
	        } else {
	            console.warn('options.result 为空');
	            return;
	        }
	    } catch (error) {
	        console.error('解析 result 失败:', error);
	        return;
	    }
	
	    console.log('解析后的结果:', this.result);
	    console.log('testId:', this.testId);
	
	    // 保存测试结果
	    let saveRes;
	    try {
	        saveRes = await uniCloud.callFunction({
	            name: 'saveMindTestResult',
	            data: {
	                testId: this.testId,
	                result: this.result,
	            }
	        });
	        console.log('云函数返回:', saveRes);
	        if (saveRes.result && saveRes.result.code === 0) {
	            console.log('保存成功:', saveRes.result.data.id);
	        } else {
	            console.error('保存失败:', saveRes);
	        }
	    } catch (err) {
	        console.error('调用云函数失败:', err);
	    }
	
	    // 如果是 testId = 1，则保存 riskLevel 到用户信息
	    if (this.testId === '1' && this.result.riskLevel) {
	        try {
	            const updateRes = await uniCloud.callFunction({
	                name: 'updateMindTestAttributes',
	                data: {
	                    uniIdToken: uni.getStorageSync('uni_id_token'),
	                    risk_level: this.result.riskLevel
	                }
	            });
	            if (updateRes.result.code === 0) {
	                console.log('用户 risk_level 更新成功');
	            } else {
	                console.error('用户信息更新失败:', updateRes.result.message);
	            }
	        } catch (err) {
	            console.error('更新用户信息失败:', err);
	        }
			//去查询推荐咨询师
			if (['中风险', '高风险'].includes(this.result.riskLevel)) {
			  this.fetchRecommendedCon();
			}
	    }
	
	    // 获取 AI 评价结果
	    try {
	        await this.getAIEstimate(saveRes.result.data.id);
	        console.log('AI 评价结果:', this.aiComment);
	    } catch (error) {
	        console.error('获取 AI 评价失败:', error.detail);
	    }
	}

};
</script>

<style>
/* 页面容器 */
.result-container {
	padding: 20px;
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 顶部标题 */
.header {
	text-align: center;
	margin-bottom: 20px;
}

.result-title {
	font-size: 24px;
	font-weight: bold;
	color: #333;
}

/* 卡片通用样式 */
.card {
	background-color: #fff;
	border-radius: 10px;
	padding: 20px;
	margin-bottom: 20px;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.card-title {
	font-size: 18px;
	font-weight: bold;
	color: #333;
	margin-bottom: 15px;
	display: block;
}

/* 风险等级卡片 */
.risk-card {
	text-align: center;
}

.risk-level {
	font-size: 28px;
	font-weight: bold;
	margin-bottom: 10px;
}

.risk-description {
	font-size: 16px;
	color: #666;
}

/* 风险等级颜色 */
.low-risk {
	color: #4caf50; /* 绿色 */
}

.medium-risk {
	color: #ff9800; /* 橙色 */
}

.high-risk {
	color: #f44336; /* 红色 */
}

/* 总均分卡片 */
.score-card {
	text-align: center;
}

.total-score {
	font-size: 36px;
	font-weight: bold;
	color: #2196f3; /* 蓝色 */
}

/* 各维度得分列表 */
.dimension-item {
	margin-bottom: 15px;
}

.dimension-name {
	font-size: 16px;
	font-weight: bold;
	color: #333;
	margin-bottom: 5px;
}

.progress-bar {
	width: 100%;
	height: 8px;
	background-color: #e0e0e0;
	border-radius: 4px;
	overflow: hidden;
	margin-bottom: 5px;
}

.progress {
	height: 100%;
	background-color: #2196f3; /* 蓝色 */
	border-radius: 4px;
}

.dimension-score {
	font-size: 14px;
	color: #666;
}

.dimension-description {
	font-size: 14px;
	color: #999;
}

/* 错误信息 */
.error-message {
	font-size: 18px;
	color: #f44336;
	text-align: center;
}

.ai-section {
	margin-top: 40rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 10px;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.ai-title {
	font-size: 18px;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	display: block;
}

.ai-loading {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx 0;
}

.ai-comment {
	font-size: 16px;
	color: #333;
	line-height: 1.6;
}

.recommend-section {
  margin-top: 30rpx;
  padding: 20rpx;
  border-radius: 20rpx;
}

.recommend-title {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.consultant-card {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
  padding: 20rpx;
  border-radius: 20rpx;
  background-color: #f6f6f6;
  margin-top: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}
.consultant-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}
.consultant-info {
  flex: 1;
}
.consultant-name {
  font-size: 30rpx;
  font-weight: bold;
}
.consultant-desc {
  font-size: 24rpx;
  color: #666;
  margin-top: 6rpx;
}

.recommend-btn {
  margin-top: 20rpx;
  margin-right: 20rpx;
}

</style>